<template>
  <Card size="small" class="share-card">
    <template #extra>
      <Button type="primary" shape="round" @click="newUser()"><PlusOutlined /> 添加</Button>
    </template>
    <Table :rowKey="getRowKey" :columns="columns" :data-source="users" @resizeColumn="resizeColumn" :scroll="{ x: 500, y: tableHeight }" :pagination="pagerOption" @change="onPaged" size="small" bordered>
      <template #bodyCell="{ column, record }">
        <div class="btn-group" v-if="column.key == 'op'">
          <Button @click="showChangeInfo(record)"> <EditOutlined /> 编辑 </Button>
          <Button type="primary" danger @click="onRemove(record)"><DeleteOutlined /> 删除</Button>
          <Button type="primary" ghost @click="showChangePassword(record)"> <KeyOutlined /> 修改密码 </Button>
          <Button type="primary" @click="setRights(record)"> <MenuOutlined /> 权限设置 </Button>
        </div>
      </template>
    </Table>
  </Card>

  <Modal v-model:visible="showNewUser" centered :maskClosable="false" title="添加新用户" :width="450" @ok="createUser">
    <Form :label-col="{ style: { width: '80px' } }">
      <Form.Item label="账号" :rules="[{ required: true }]">
        <Input v-model:value="userInfo.account" />
      </Form.Item>
      <Form.Item label="密码" :rules="[{ required: true }]">
        <Input.Password v-model:value="userInfo.password" />
      </Form.Item>
      <Form.Item label="确认密码" :rules="[{ required: true }]">
        <Input.Password v-model:value="userInfo.confirmPassword" />
      </Form.Item>
      <Form.Item label="姓名" :rules="[{ required: true }]">
        <Input v-model:value="userInfo.userName" />
      </Form.Item>
      <Form.Item label="邮箱">
        <Input v-model:value="userInfo.email" type="email" />
      </Form.Item>
    </Form>
  </Modal>

  <Modal v-model:visible="showUserEdit" centered :maskClosable="false" title="修改用户信息" :width="450" @ok="changeInfo">
    <Form :label-col="{ style: { width: '80px' } }">
      <Form.Item label="账号" :rules="[{ required: true }]">
        <Input v-model:value="userInfo.account" :disabled="true" />
      </Form.Item>
      <Form.Item label="姓名" :rules="[{ required: true }]">
        <Input v-model:value="userInfo.userName" />
      </Form.Item>
      <Form.Item label="邮箱">
        <Input v-model:value="userInfo.email" type="email" />
      </Form.Item>
    </Form>
  </Modal>

  <Modal v-model:visible="showChgPasswordEdit" centered :maskClosable="false" title="修改密码" :width="450" @ok="changePassword">
    <Form :label-col="{ style: { width: '80px' } }" autocomplete="off">
      <Form.Item label="旧密码" :rules="[{ required: true }]">
        <Input.Password v-model:value="chgPassword.oldPassword" />
      </Form.Item>
      <Form.Item label="新密码" :rules="[{ required: true }]">
        <Input.Password v-model:value="chgPassword.newPassword" />
      </Form.Item>
      <Form.Item label="确认密码" :rules="[{ required: true }]">
        <Input.Password v-model:value="chgPassword.confirmPassword" />
      </Form.Item>
    </Form>
  </Modal>
</template>
<script setup>
  import md5 from 'js-md5';
  import { useStore } from 'vuex';
  import { useRouter } from 'vue-router';
  import { ref, reactive, toRaw, computed, inject, onMounted } from 'vue';
  import { Card, Button, Table, Modal, Form, Input } from 'ant-design-vue';
  import { PlusOutlined, KeyOutlined, EditOutlined, MenuOutlined, DeleteOutlined } from '@ant-design/icons-vue';

  const $store = useStore();
  const $router = useRouter();

  const $http = inject('$http');
  const $modal = inject('$modal');
  const $message = inject('$message');

  const users = ref([]);
  const showNewUser = ref(false);
  const showUserEdit = ref(false);
  const showChgPasswordEdit = ref(false);

  const pagerOption = reactive({
    current: 1,
    pageSize: 20,
    defaultPageSize: 20,
    total: 0
  });
  const so = reactive({
    level: '',
    keywords: ''
  });

  const userInfo = reactive({});

  const chgPassword = reactive({
    account: '',
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  });

  const columns = reactive([
    {
      title: '序号',
      width: 30,
      resizable: false,
      align: 'center',
      customRender: ({ index }) => (pagerOption.current - 1) * pagerOption.pageSize + index + 1
    },
    { title: '账号', width: 80, resizable: true, dataIndex: 'Account' },
    { title: '用户名', width: 50, resizable: true, dataIndex: 'UserName' },
    { title: '邮箱', width: 150, resizable: true, dataIndex: 'EMail' },
    { title: '创建时间', width: 100, resizable: true, dataIndex: 'CreatedOn' },
    { title: '最后一次登录时间', width: 100, resizable: true, dataIndex: 'LastLogOn' },
    { key: 'op', fixed: 'right', align: 'center', width: 230 }
  ]);

  const tableHeight = computed(() => {
    return $store.state.area.content.height - 180;
  });

  function getRowKey(record) {
    return 'tr' + record.Code;
  }

  function resizeColumn(w, col) {
    col.width = w;
  }

  function onPaged(pg) {
    let index = 1;

    if (pg && pg.current) {
      index = pg.current;
      pagerOption.pageSize = pg.pageSize;
    }

    let searchObject = {
      pageIndex: index,
      pageSize: pagerOption.pageSize,
      account: so.account,
      userName: so.userName
    };

    $http.post('/api/rbac/users/search', searchObject).then(res => {
      users.value = res.datas;

      pagerOption.current = index || 1;
      pagerOption.total = res.total;
    });
  }

  function onReset() {
    so.account = '';
    so.userName = '';
  }

  function newUser() {
    userInfo.id = null;
    userInfo.account = '';
    userInfo.password = '';
    userInfo.confirmPassword = '';
    userInfo.userName = '';
    userInfo.email = '';

    showNewUser.value = true;
  }

  function showChangeInfo(item) {
    userInfo.id = item.Id;
    userInfo.account = item.Account;
    userInfo.userName = item.UserName;
    userInfo.email = item.EMail;

    showUserEdit.value = true;
  }

  function showChangePassword(item) {
    chgPassword.account = item.Account;
    chgPassword.oldPassword = '';
    chgPassword.newPassword = '';
    chgPassword.confirmPassword = '';

    showChgPasswordEdit.value = true;
  }

  function createUser() {
    let msgKey = 'valid-create';

    if (!userInfo.account) {
      $message.error({ key: msgKey, content: '账号不能为空！' });

      return false;
    }

    if (!userInfo.password) {
      $message.error({ key: msgKey, content: '密码不能为空！' });

      return false;
    }

    if (userInfo.password != userInfo.confirmPassword) {
      $message.error({ key: msgKey, content: '确认密码和密码不同！' });

      return false;
    }

    $http.post('/api/account/create', toRaw(userInfo)).then(res => {
      if (res.success) {
        showNewUser.value = false;

        $message.success('添加成功！');

        onPaged();
      } else {
        $message.error({ key: msgKey, content: res.message });
      }
    });
  }

  function changeInfo() {
    let item = {
      id: userInfo.id,
      account: userInfo.account,
      userName: userInfo.userName,
      email: userInfo.email
    };

    $http.put('/api/account/update', item).then(res => {
      if (res.success) {
        showUserEdit.value = false;

        $message.success('修改成功！');

        onPaged();
      } else {
        $message.error({ key: 'chg', content: res.message });
      }
    });
  }

  function changePassword() {
    showChgPasswordEdit.value = true;
    chgPassword.oldPassword = md5(chgPassword.oldPassword);

    $http.post('/api/account/changePassword', toRaw(chgPassword)).then(res => {
      if (res.success) {
        showChgPasswordEdit.value = false;

        $message.success('修改成功！');
      } else {
        $message.error({ key: 'chg', content: res.message });
      }
    });
  }

  function onRemove(item) {
    $modal.confirm({
      title: '警告',
      content: '是否确定删除该用户？',
      onOk: () => {
        $http.delete(`/api/account/${item.Id}`).then(res => {
          if (res.success) {
            $message.success('删除成功！');

            onPaged();
          } else {
            $message.error({ key: 'delete', content: res.message });
          }
        });
      }
    });
  }

  function setRights(rd) {
    $router.push({ path: '/rbac/user/rights', query: { id: rd.Id, name: rd.UserName, type: 'user' } });
  }

  onMounted(() => {
    onPaged();
  });
</script>
